package com.woniuxy.userassembly.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniu.cloud.api.*;
import com.woniu.cloud.api.platformAccount.PlatformAccountApi;
import com.woniu.cloud.api.serve.ServeApi;
import com.woniu.cloud.common.dto.Result;
import com.woniu.cloud.common.exception.TicketException;
import com.woniu.cloud.entity.*;
import com.woniu.cloud.form.InsertPlatformAccountForm;
import com.woniu.cloud.form.InsertServiceCommissionForm;
import com.woniu.cloud.form.PlatformRevenueForm;
import com.woniu.cloud.form.StoreRevenueInsertForm;
import com.woniuxy.api.*;
import com.woniuxy.cloud.UserAPI;
import com.woniuxy.cloud.entity.TGoodCar;
import com.woniuxy.cloud.entity.TServiceCar;
import com.woniuxy.cloud.entity.TUser;
import com.woniuxy.cloud.entity.TUserCoupon;
import com.woniuxy.cloud.form.AddCouponForm;
import com.woniuxy.cloud.form.AddUserServiceProcessForm;
import com.woniuxy.entity.*;
import com.woniuxy.form.*;
import com.woniuxy.userassembly.common.RandomUtil;
import com.woniuxy.userassembly.config.AlipayConfig;
import com.woniuxy.userassembly.config.RabbitConfig;
import com.woniuxy.userassembly.config.RabbitProducerConfigDelay;
import com.woniuxy.userassembly.service.PaymentServiceImpl;
import com.woniuxy.userassembly.util.JwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
//@RequestMapping("/price")
@SuppressWarnings("all")
@Api(tags = "业务流程", description = "用户下单充值，取消订单 等到相关")
@Slf4j
@CrossOrigin(origins = {" * "}, allowedHeaders="*")
@GlobalTransactional
public class PriceApiImp implements PriceApi {



    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    UserAPI userAPI;

    @Resource
    StoreRevenueApi storeRevenueApi;

    @Resource
    PlatformAccountApi platformAccountApi;

    @Resource
    GoodOrderApi goodOrderApi;

    @Resource
    MarketingApi marketingApi;

    @Resource
    StoreGoodApi storeGoodApi;

    @Resource
    ServiceOrderApi serviceOrderApi;

    @Resource
    ScoreGoodApi scoreGoodApi;

    @Resource
    PaymentServiceImpl paymentService;

    @Resource
    ScoreOrderApi scoreOrderApi;

    @Resource
    ProductOrderDetailApi productOrderDetailApi;

    @Resource
    ServiceOrderDetailApi serviceOrderDetailApi;

    @Resource
    StoreServiceMiddleApi storeServiceMiddleApi;

    @Resource
    ServeApi serveApi;

    @Resource
    AlipayConfig alipayConfig;



    /**
     * 将该笔流水计入平台收益表中,增加收益
     * @param userBalance 充值余额
     * @return
     */
    @PostMapping("/addUserBalanceByUserId")
    @ApiOperation("用户充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userBalance", value = "充值金额", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    @GlobalTransactional
    public Result addUserBalanceByUserId(Double userBalance) {
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        log.info("{}",userId);
        //完成充值
        Result result = userAPI.addUserBalanceByUserId(userId,userBalance);
        //往流水表中添加数据
        PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
        platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(userBalance));
        platformRevenueForm.setPlatformRevenueRetype("EARNINGS");
        platformRevenueForm.setPlatformRevenueType(4);
        //通过JWT获取userId
        platformRevenueForm.setPlatformRevenueUserId(userId);
        Result result1 = platformAccountApi.insertPlatformRevenue(platformRevenueForm);
        return result1;
    }

    @PutMapping("/userWithdrawalByUserId")
    @ApiOperation("根据用户id进行提现")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userBalance", value = "提现金额", dataType = "Double"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = Boolean.class)
    })
    @Override
    public Result userBalanceByUserId(Double userBalance) {
        Integer userId =JwtUtil.getUserId();
        userAPI.withdraw(userId,userBalance);
        //往流水表中添加数据
        PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
        platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(userBalance));
        platformRevenueForm.setPlatformRevenueRetype("EXPEND");
        platformRevenueForm.setPlatformRevenueType(5);
        //通过JWT获取userId
        platformRevenueForm.setPlatformRevenueUserId(userId);
        Result result1 = platformAccountApi.insertPlatformRevenue(platformRevenueForm);
        return result1;
    }


    @PutMapping("/userWithdrawalCallback")
    @ApiOperation("用户提现回调")
    @ApiImplicitParams({
    })
    @ApiResponses({
    })
    @Override
    public void userWithdrawalCallback() {

    }

    /**
     * 支付宝充值
     * @param userBalance
     * @return
     */
    @PostMapping("/updateUserBalance")
    public Result updateUserBalance(Double userBalance){
        //获取用户id
        Integer userId = JwtUtil.getUserId();
        log.info("用户id={},充值余额={}",userId,userBalance);
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(userId+"");
        alipayBean.setSubject("余额充值");
        alipayBean.setTotal_amount(userBalance);
        String result = paymentService.toAlipay(alipayBean,1);
        return Result.success("成功",result);
    }


    /**
     * 充值回调
     * @param request
     * @return
     */
    @PostMapping("/userBalanceBack")
    public Result userBalanceBack(HttpServletRequest request){
        System.err.println("进入余额充值支付回调函数");
        log.info("进入支付回调函数");
        Map<String, String[]> map = request.getParameterMap();
        String[] out_trade_nos = map.get("out_trade_no");
        String[] total_amounts = map.get("total_amount");
        //获取用户id
        Integer userId =Integer.parseInt(out_trade_nos[0]);
        //获取充值余额
        double userBalance = Double.parseDouble(total_amounts[0]);

        Result result = userAPI.addUserBalanceByUserId(userId,userBalance);
        //往流水表中添加数据
        PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
        platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(userBalance));
        platformRevenueForm.setPlatformRevenueRetype("收入");
        platformRevenueForm.setPlatformRevenueType(4);
        //通过JWT获取userId
        platformRevenueForm.setPlatformRevenueUserId(userId);
        Result result1 = platformAccountApi.insertPlatformRevenue(platformRevenueForm);
        return result1;
    }





    /**
     *
     *             "新增用户订单详情\n" +
     *             "门店修改商品库存\n" +
     *             "商品移除购物车\n" +
     *             "(如果使用了优惠券)减少优惠券\n" +
     *             "同时生成一个15分钟的延迟队列，对该笔订单进行监控，如果没付款则自动取消
     * @param settlementShoppingCart 购物车详情
     * @return
     */
    @PostMapping("/updateSettlementShoppingCart")
    @ApiOperation("新增用户商品订单，生成待支付订单")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateSettlementShoppingCart(SettlementShoppingCart settlementShoppingCart) {
        Integer userId = JwtUtil.getUserId();
        log.info("====进入到方法中 参数为 ={}",settlementShoppingCart);
        String s = JSON.toJSONString(settlementShoppingCart.getGoodCarId());

        //1.加入订单  创建待支付订单，创建商品订单详情
        InsertGoodOrder insertGoodOrder = new InsertGoodOrder();
        if(settlementShoppingCart.getCoupon()==null||settlementShoppingCart.getCoupon()==0){
            insertGoodOrder.setGoodOrderTotal(new BigDecimal(settlementShoppingCart.getTotal()));
            insertGoodOrder.setGoodOrderPracticalTotal(new BigDecimal(settlementShoppingCart.getTotal()));
        }else {
            //减少优惠券
            userAPI.updateUserCouponNumByUserCouponId(settlementShoppingCart.getCoupon(),1);
            Result couponByConponId = marketingApi.getCouponByConponId(settlementShoppingCart.getCoupon());
            Object data = couponByConponId.getData();
            TCoupon tCoupon = JSON.parseObject(JSON.toJSONString(data), TCoupon.class);
            insertGoodOrder.setGoodOrderTotal(new BigDecimal(settlementShoppingCart.getTotal()));
            insertGoodOrder.setGoodOrderPracticalTotal(new BigDecimal(settlementShoppingCart.getTotal()-tCoupon.getCouponPrice()));
        }
        insertGoodOrder.setGoodOrderCreateTime(new Date());
//        insertGoodOrder.setGoodOrderPayType(settlementShoppingCart.getPayType());


//        insertGoodOrder.setGoodOrderUserId(userId);

        insertGoodOrder.setGoodOrderDeliveryMethod(settlementShoppingCart.getDeliveryMethod());
        insertGoodOrder.setGoodOrderStoreId(settlementShoppingCart.getStoreId());
        List<Integer> ids = settlementShoppingCart.getGoodCarId();
        Result goodCarByIds = userAPI.getGoodCarByIds(s);
        List<TGoodCar> tGoodCars = JSON.parseArray(JSON.toJSONString(goodCarByIds.getData()), TGoodCar.class);
        List<Integer> idss = new ArrayList<>();
        List<Integer> nums = new ArrayList<>();
        for (TGoodCar tGoodCar : tGoodCars) {
            System.err.println(tGoodCar);
            idss.add(tGoodCar.getGoodCarStoreGoodId());
            nums.add(tGoodCar.getGoodCarNum());

            //门店减少商品库存  增加销量
            storeGoodApi.updateStoreGoodNumByStoreGoodId(tGoodCar.getGoodCarStoreGoodId(),-tGoodCar.getGoodCarNum());
            storeGoodApi.updateStoreGoodSellNumByStoreGoodId(tGoodCar.getGoodCarStoreGoodId(),tGoodCar.getGoodCarNum());
            //移除购物车
            //todo 为了测试先注释掉
            userAPI.deleteGoodCarByGoodCarId(tGoodCar.getGoodCarId());
        }
        insertGoodOrder.setGoodIdList(idss);
        insertGoodOrder.setGoodNumList(nums);
        Result result1 = goodOrderApi.insertGoodOrder(insertGoodOrder);
        Integer goodOrderId = JSONObject.parseObject(JSON.toJSONString(result1.getData()), Integer.class);

        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setTotal_amount(settlementShoppingCart.getTotal());
        alipayBean.setOut_trade_no(RandomUtil.randomStr(17));
        alipayBean.setSubject(goodOrderId.toString());
        alipayBean.setBody(s);
        alipayBean.setVid(1);
        goodOrderCancel(goodOrderId);
        String result = paymentService.toAlipay(alipayBean,null);
        //todo 生成一个15分钟的延迟队列，对该笔订单进行监控，如果没付款则自动取消


        return Result.success("成功",result);
    }

    @ApiOperation("rabbitmq 取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Integer"),
            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    public Result goodOrderCancel(Integer orderId) {
        log.info("进入延迟任务");
        rabbitTemplate.convertAndSend(RabbitProducerConfigDelay.EXCHANGE_NAME,
                RabbitProducerConfigDelay.ROUTING_NAME,
                orderId,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setHeader("x-delay",2*1000);
                        return message;
                    }
                }
        );
        return null;
    }

    @RabbitListener(queues = "QUEUE_SPRING_BOOT_DELAY")
    public void getMesE(Integer goodOrderId){
        log.info("延迟");
        Result goodOrderById = goodOrderApi.getGoodOrderById(goodOrderId);
        GoodOrder goodOrder = JSON.parseObject(JSON.toJSONString(goodOrderById.getData()), GoodOrder.class);
        if(goodOrder.getGoodOrderStatus()==0){
            updateCancelShoppingOrder(goodOrderId);
        }
    }
//    @PostMapping("/test")
//    @ApiOperation("用户支付 商品待支付订单，修改成已支付订单")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Integer"),
//            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
//    })
//    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
//    public Result test(Integer orderId,Double price) {
//        log.info("测试  orderId={},price={}",orderId,price);
//        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_EXCHANGE,
//                RabbitConfig.ORDER_ROUTING_KEY,
//                orderId+price,
//                new MessagePostProcessor() {
//                    @Override
//                    public Message postProcessMessage(Message message) throws AmqpException {
//                        message.getMessageProperties().setExpiration(""+1000);
//                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
//                        return message;
//                    }
//                }
//        );
//        return null;
//    }

//    @RabbitListener(queues = "dlx.queue")
//    public void getMesE(Object msg){
//        log.info("死信队列接收到消息{}",msg);
//    }

    @PostMapping("payback")
    public Result allBack(HttpServletRequest request){
        System.err.println("进入支付回调函数");
        log.info("进入支付回调函数");

        Map<String, String[]> map = request.getParameterMap();
        String[] total_amounts = map.get("total_amount");
        double total = Double.parseDouble(total_amounts[0]);
        log.info("total参数：{}",total);
        String[] bodies = map.get("body");
        String[] vids1 = map.get("vid");
        String s = vids1[0];
        System.err.println("s===="+s);
        String[] vids = map.get("subject");
        String vid1 = vids[0];
        Integer vid = Integer.parseInt(vid1);
        System.err.println("vid="+vid+"----------total="+total);

        updatePayOrder(vid,total,1);
        return null;
    }
    /**
     * 减少平台收益表，减少用户余额(如果是用户余额支付)\n" +
     *             "增加门店收益\n" +
     *             "增加用户积分的接口\n" +
     *             "修改订单状态
     * @param orderId 订单编号
     * @return
     */
    @PutMapping("/updatePayOrder")
    @ApiOperation("用户支付 商品待支付订单，修改成已支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Integer"),
            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updatePayOrder(Integer orderId,Double price,Integer payType) {
//        Integer userId = 1;
        //如果是余额支付
        Result goodOrderById = goodOrderApi.getGoodOrderById(orderId);
        GoodOrder goodOrder = JSONObject.parseObject(JSON.toJSONString(goodOrderById.getData()), GoodOrder.class);
        Integer userId = goodOrder.getGoodOrderUserId();
        goodOrderApi.updateGoodOrderPayType(orderId,payType);
        if(payType==2){
            Integer goodOrderUserId = goodOrder.getGoodOrderUserId();
            Result userByUserId = userAPI.getUserByUserId(userId);
            TUser tUser = JSONObject.parseObject(JSON.toJSONString(userByUserId), TUser.class);
            Double userBalance = tUser.getUserBalance();
            if (userBalance<price){
                throw new TicketException("余额不足");
            }
            PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
            platformRevenueForm.setPlatformRevenueUserId(tUser.getUserId());
            platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(price));
            platformRevenueForm.setPlatformRevenueRetype("EXPEND");
            platformRevenueForm.setPlatformRevenueType(6);
            //todo 等待revenue orderId;
            platformAccountApi.insertPlatformRevenue(platformRevenueForm);
            userAPI.updateUserBalnceByUserId(userId,price);
        }

        //增加门店收益

        StoreRevenueInsertForm storeRevenueInsertForm = new StoreRevenueInsertForm();
        storeRevenueInsertForm.setStoreRevenueStoreId(goodOrder.getGoodOrderStoreId());
        storeRevenueInsertForm.setStoreRevenueType(4);
        storeRevenueInsertForm.setStoreRevenuePrice(price);
        storeRevenueInsertForm.setStoreRevenueRetype(1);
        storeRevenueInsertForm.setStoreRevenueStoreGoodOrderId(orderId);
        storeRevenueApi.insertStoreRevenue(storeRevenueInsertForm);

        //增加用户积分
        Integer score= new Double(price/10).intValue();
        userAPI.addUserScoreByUserId(userId,score);

        //修改订单状态
        Result result = goodOrderApi.updateGoodOrderPaied(orderId);


        return result;
    }

    /**
     * 新增用户服务订单\n" +
     *             "新增用户订单详情\n" +
     *             "服务商品移除购物车\n" +
     *             抽成
     *             "(如果使用了优惠券)减少优惠券\n" +
     *             "同时生成一个15分钟的延迟队列，对该笔点订单进行监控，如果没付款则自动取消
     * @param serviceSettlementShoppingCart 服务购物车详情
     * @return
     */
    @PostMapping("/insertServiceCarSettlement")
    @ApiOperation("用户结算服务购物车生成服务待支付订单")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result insertServiceCarSettlement(@RequestBody ServiceSettlementShoppingCart serviceSettlementShoppingCart) {
        //todo 通过jwt 获取userId
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        System.err.println(userId);
        //1.加入订单  创建待支付订单，创建商品订单详情
        InsertServiceOrder insertGoodOrder = new InsertServiceOrder();
        if(serviceSettlementShoppingCart.getCoupon()==null||serviceSettlementShoppingCart.getCoupon()==0){
            insertGoodOrder.setServiceOrderTotal(new BigDecimal(serviceSettlementShoppingCart.getTotal()));
            insertGoodOrder.setServiceOrderPracticalTotal(new BigDecimal(serviceSettlementShoppingCart.getTotal()));
        }else {
            //减少优惠券
            userAPI.updateUserCouponNumByUserCouponId(serviceSettlementShoppingCart.getCoupon(),1);
            System.err.println("============================"+serviceSettlementShoppingCart.getCoupon());
            Result userCouponById = userAPI.getUserCouponById(serviceSettlementShoppingCart.getCoupon());
            TUserCoupon tUserCoupon = JSON.parseObject(JSON.toJSONString(userCouponById.getData()), TUserCoupon.class);
            System.err.println(tUserCoupon);
            Result couponByConponId = marketingApi.getCouponByConponId(tUserCoupon.getUserCouponCouponId());
            Object data = couponByConponId.getData();
            TCoupon tCoupon = JSON.parseObject(JSON.toJSONString(data), TCoupon.class);
            System.err.println(tCoupon);

            insertGoodOrder.setServiceOrderTotal(new BigDecimal(serviceSettlementShoppingCart.getTotal()));
            BigDecimal bigDecimal = new BigDecimal(serviceSettlementShoppingCart.getTotal() - tCoupon.getCouponPrice());
            insertGoodOrder.setServiceOrderPracticalTotal(bigDecimal);
        }
        insertGoodOrder.setServiceOrderCreateTime(new Date());
        insertGoodOrder.setServiceOrderStoreId(serviceSettlementShoppingCart.getStoreId());
        Result serviceCarByIds = userAPI.getServiceCarByIds(serviceSettlementShoppingCart.getGoodCarId());
        List<TServiceCar> tGoodCars = JSON.parseArray(JSON.toJSONString(serviceCarByIds.getData()), TServiceCar.class);
        List<Integer> ids = new ArrayList<>();
        List<Integer> nums = new ArrayList<>();
        for (TServiceCar tGoodCar : tGoodCars) {
            ids.add(tGoodCar.getServiceCarSecondServiceId());
            nums.add(tGoodCar.getServiceCarNum());

            //移除购物车
            userAPI.deleteServiceCarByServiceCarId(tGoodCar.getServiceCarId());
        }
        insertGoodOrder.setSecondService(ids);
        insertGoodOrder.setSecondServiceNum(nums);
        insertGoodOrder.setServiceOrderUserId(userId);
        Result result = serviceOrderApi.insertServiceOrder(insertGoodOrder);


        //todo 生成一个15分钟的延迟队列，对该笔订单进行监控，如果没付款则自动取消


        return result;
//        return null;
    }

    @GetMapping("/serviceOrderCancel")
    @ApiOperation("rabbitmq 取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Integer"),
            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    public Result serviceOrderCancel(Integer orderId) {
        log.info("进入服务延迟任务");
        rabbitTemplate.convertAndSend(RabbitProducerConfigDelay.EXCHANGE_NAME,
                RabbitProducerConfigDelay.ROUTING_NAME1,
                orderId,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setHeader("x-delay",2*1000);
                        return message;
                    }
                }
        );
        return null;
    }

    @RabbitListener(queues = "QUEUE_SPRING_BOOT_DELAY1")
    public void getServiceOrderCancel(Integer goodOrderId){
        log.info("服务延迟");
        Result goodOrderById = goodOrderApi.getGoodOrderById(goodOrderId);
        GoodOrder goodOrder = JSON.parseObject(JSON.toJSONString(goodOrderById.getData()), GoodOrder.class);
        if(goodOrder.getGoodOrderStatus()==0){
            updateCancelServiceOrder(goodOrderId);
        }
    }


    Integer rid=0;
    /**
     * 减少平台收益表，增加平台收益表，减少用户余额(如果是用户余额支付)\n" +
     *             "增加门店收益\n" +
     *             "增加用户积分的接口\n" +
     *             "修改订单状态\n" +
     *             "增加平台收益\n" +
     *             "生成用户服务流程表
     * @param serviceOrderId 服务订单Id
     * @return
     */
    @PutMapping("/updateServiceOrderPay")
    @ApiOperation("用户支付 服务待支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceOrderId", value = "服务订单Id", dataType = "Integer"),
            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateServiceOrderPay(Integer serviceOrderId,Double price,Integer payType) {
        //todo 通过jwt 获取userId

//        Integer userId = 1;

        Result goodOrderById = serviceOrderApi.getServiceOrderById(serviceOrderId);
        ServiceOrder goodOrder = JSONObject.parseObject(JSON.toJSONString(goodOrderById.getData()), ServiceOrder.class);
        System.err.println("=========="+goodOrder);
        Integer userId = goodOrder.getServiceOrderUserId();
        System.err.println("======="+userId);
        serviceOrderApi.updateServiceOrderPayType(serviceOrderId,payType);
        if(payType==2){
            //如果是余额支付 就有特殊操作
            Result userByUserId = userAPI.getUserByUserId(userId);
            System.err.println("=============================="+userByUserId);
            TUser tUser = JSONObject.parseObject(JSON.toJSONString(userByUserId.getData()), TUser.class);
            Double userBalance = tUser.getUserBalance();
            System.err.println(tUser);
            if (userBalance<price){
                throw new TicketException("余额不足");
            }
            PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
            platformRevenueForm.setPlatformRevenueUserId(tUser.getUserId());
            platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(price));
            platformRevenueForm.setPlatformRevenueRetype("EXPEND");
            platformRevenueForm.setPlatformRevenueType(6);
            platformAccountApi.insertPlatformRevenue(platformRevenueForm);
            //todo 等待revenue orderId;
            userAPI.updateUserBalnceByUserId(userId,price);
        }
        //增加门店收益
        StoreRevenueInsertForm storeRevenueInsertForm = new StoreRevenueInsertForm();
        storeRevenueInsertForm.setStoreRevenueStoreId(goodOrder.getServiceOrderStoreId());
        storeRevenueInsertForm.setStoreRevenueType(3);
        storeRevenueInsertForm.setStoreRevenuePrice(price);
        storeRevenueInsertForm.setStoreRevenueRetype(1);
        storeRevenueInsertForm.setStoreRevenueServiceOrderId(serviceOrderId);
        storeRevenueApi.insertStoreRevenue(storeRevenueInsertForm);

        //增加用户积分
        Integer score= new Double(price/10).intValue();
        userAPI.addUserScoreByUserId(userId,score);
        //修改订单状态
        Result result = serviceOrderApi.updateServiceOrderStatus(serviceOrderId,1);
        System.err.println("serviceOrderId="+serviceOrderId);
        //查询该服务订单的所有订单详情
        Result serviceOrderDetailByProductOrderId = serviceOrderDetailApi.getServiceOrderDetailByProductOrderId(serviceOrderId);
        List<ServiceOrderDetail> serviceOrderDetail = JSON.parseArray(JSON.toJSONString(serviceOrderDetailByProductOrderId.getData()), ServiceOrderDetail.class);
        Double commition = 0.0;
        for (ServiceOrderDetail orderDetail : serviceOrderDetail) {
            BigDecimal serviceOrderDetailTotal = orderDetail.getServiceOrderDetailTotal();
            Integer serviceOrderDetailSecondServiceId = orderDetail.getServiceOrderDetailSecondServiceId();
            System.err.println("serviceOrderDetailSecondServiceId="+serviceOrderDetailSecondServiceId);
            Result storeServiceMiddleById = storeServiceMiddleApi.getStoreServiceMiddleById(serviceOrderDetailSecondServiceId);
            TStoreServiceMiddle storeServiceMiddle = JSONObject.parseObject(JSON.toJSONString(storeServiceMiddleById.getData()), TStoreServiceMiddle.class);
            System.err.println("storeServiceMiddle="+storeServiceMiddle);
            Double storeServiceMiddleCommition = storeServiceMiddle.getStoreServiceMiddleCommition();
            Double value = serviceOrderDetailTotal.doubleValue();
            System.err.println(value);
            System.err.println(storeServiceMiddleCommition);
            commition += value * storeServiceMiddleCommition; //抽成金额
            Double v = value * storeServiceMiddleCommition;

            //增加平台抽成数据
            InsertServiceCommissionForm insertServiceCommissionForm = new InsertServiceCommissionForm();
            insertServiceCommissionForm.setServiceCommissionTime(new Date());
            insertServiceCommissionForm.setServiceCommissionSecondServiceId(serviceOrderDetailSecondServiceId);
            insertServiceCommissionForm.setServiceCommissionCommissionPrice(new BigDecimal(v));
            insertServiceCommissionForm.setServiceCommissionStoreId(goodOrder.getServiceOrderStoreId());
            Result result1 = serveApi.insertServiceCommission(insertServiceCommissionForm);
            ServiceCommission serviceCommission = JSONObject.parseObject(JSON.toJSONString(result1.getData()), ServiceCommission.class);
            System.err.println("serviceCommission="+serviceCommission);

            rid = serviceCommission.getServiceCommissionId();
            //增加平台流水
            PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
            platformRevenueForm.setPlatformRevenueRetype("EARNINGS");
            platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(v));
            platformRevenueForm.setPlatformRevenueUserId(userId);
            platformRevenueForm.setPlatformRevenueServiceCommissionId(rid);
            platformRevenueForm.setPlatformRevenueType(3);
            platformAccountApi.insertPlatformRevenue(platformRevenueForm);

            //添加用户服务流程
            AddUserServiceProcessForm addUserServiceProcessForm = new AddUserServiceProcessForm();
            addUserServiceProcessForm.setUserServiceProcessSecondServiceId(serviceOrderDetailSecondServiceId);
            addUserServiceProcessForm.setUserServiceProcessServiceOrderDetailId(orderDetail.getServiceOrderDetailId());
            Result serviceProcess = serveApi.getServiceProcess(serviceOrderDetailSecondServiceId);
            List<ServiceProcess> serviceProcesses = JSONObject.parseArray(JSON.toJSONString(serviceProcess.getData()), ServiceProcess.class);
            for (ServiceProcess process : serviceProcesses) {
                addUserServiceProcessForm.setUserServiceProcessServiceProcessId(process.getServiceProcessId());
                userAPI.createUserServiceProcess(addUserServiceProcessForm);
            }

        }

        return result;
    }

    /**
     * 减少商品库存\n" +
     *             "修改积分商品的销量\n" +
     *             "生成积分订单\n" +
     *             "同时生成一个15分钟的延迟队列，对该笔点订单进行监控，如果没付款则自动取消
     * @param scoreGoodId 积分商品id
     * @return
     */
    @PutMapping("/insertUserPayScoreGood")
    @ApiOperation("用户下单积分商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "scoreGoodId", value = "积分商品id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result insertUserPayScoreGood(Integer scoreGoodId) {
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        //查询用户信息
        Result userByUserId = userAPI.getUserByUserId(userId);
        TUser tUser = JSONObject.parseObject(JSON.toJSONString(userByUserId.getData()), TUser.class);

        Result scoreGoodByScoreGoodId = scoreGoodApi.getScoreGoodByScoreGoodId(scoreGoodId);
        TScoreGood scoreGood = JSONObject.parseObject(JSON.toJSONString(scoreGoodByScoreGoodId.getData()), TScoreGood.class);

        if(tUser.getUserScore()<scoreGood.getScoreGoodScorePrice()){
            throw new TicketException("积分不足 下单失败");
        }

        //减少商品库存
        scoreGoodApi.updateScoreGoodNumByScoreGoodId(scoreGoodId,-1);

        //修改积分商品的销量
        scoreGoodApi.updateScoreGoodSellNumByScoreGoodId(scoreGoodId,1);

        //生成积分订单
        InsertScoreOrder insertScoreOrder = new InsertScoreOrder();
        insertScoreOrder.setScoreOrderBuyTime(new Date());
        insertScoreOrder.setScoreOrderScoreGoodId(scoreGoodId);
        insertScoreOrder.setUserId(tUser.getUserId());
        insertScoreOrder.setScoreOrderScoreTotal(scoreGood.getScoreGoodScorePrice());
        insertScoreOrder.setScoreOrderStatus(0);
        scoreOrderApi.insertScoreOrder(insertScoreOrder);


        //todo 同时生成一个15分钟的延迟队列，对该笔点订单进行监控，如果没付款则自动取消

        return Result.success("下单成功",true);
    }

    @PutMapping("/updatePayScoreGoodOrder")
    @ApiOperation("购买积分商品待支付积分商品订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "scoreServiceId", value = "积分订单id", dataType = "Integer"),
            @ApiImplicitParam(name = "price", value = "金额", dataType = "Double"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updatePayScoreGoodOrder(Integer scoreGoodId,Double price) {
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        Result userByUserId = userAPI.getUserByUserId(userId);
        TUser tUser = JSONObject.parseObject(JSON.toJSONString(userByUserId.getData()), TUser.class);

        Result scoreGoodByScoreGoodId = scoreGoodApi.getScoreGoodByScoreGoodId(scoreGoodId);
        TScoreGood scoreGood = JSONObject.parseObject(JSON.toJSONString(scoreGoodByScoreGoodId.getData()), TScoreGood.class);
        if(tUser.getUserScore()<scoreGood.getScoreGoodScorePrice()){
            throw new TicketException("积分不足 支付失败");
        }
        Result result = scoreOrderApi.updateScoreOrderStatus(scoreGoodId, 1);
        //todo  用户减少积分
        userAPI.reduceUserScoreByUserId(userId,scoreGood.getScoreGoodScorePrice());

        return result;
    }

    /**
     * 修改订单状态\n" +
     *             "如果使用优惠劵（增加优惠劵）\n" +
     *             "修改商品库存
     * @param orderId
     * @return
     */
    @PutMapping("/updateCancelShoppingOrder")
    @ApiOperation("取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "商品订单id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateCancelShoppingOrder(Integer orderId) {

//        todo 拿到userId
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        Result goodOrderById = goodOrderApi.getGoodOrderById(orderId);
        GoodOrder goodOrder = JSONObject.parseObject(JSON.toJSONString(goodOrderById.getData()), GoodOrder.class);

        //修改订单状态
        Result result = goodOrderApi.updateGoodOrderStatus(orderId);

        //判断是否使用了优惠券
        BigDecimal goodOrderPracticalTotal = goodOrder.getGoodOrderPracticalTotal();
        BigDecimal goodOrderTotal = goodOrder.getGoodOrderTotal();
        double price = goodOrderTotal.doubleValue() - goodOrderPracticalTotal.doubleValue();
        if(price!=0){
            Result couponByPrice = marketingApi.getCouponByPrice(price);
            TCoupon coupon = JSONObject.parseObject(JSON.toJSONString(couponByPrice.getData()), TCoupon.class);
            AddCouponForm addCouponForm = new AddCouponForm();
            addCouponForm.setUserId(userId);
            addCouponForm.setCouponId(coupon.getCouponId());
            addCouponForm.setNumber(1);
            userAPI.insetCouponByUserId(addCouponForm);
        }

        //返回商品库存
        Result productOrderDetailByProductOrderId = productOrderDetailApi.getProductOrderDetailByProductOrderId(orderId);
        List<ProductOrderDetail> tGoodCars = JSON.parseArray(JSON.toJSONString(productOrderDetailByProductOrderId.getData()), ProductOrderDetail.class);
        for (ProductOrderDetail tGoodCar : tGoodCars) {
            storeGoodApi.updateStoreGoodNumByStoreGoodId(tGoodCar.getProductOrderDetailStoreGoodId(),tGoodCar.getProductOrderDetailNum());
            storeGoodApi.updateStoreGoodSellNumByStoreGoodId(tGoodCar.getProductOrderDetailStoreGoodId(),-tGoodCar.getProductOrderDetailNum());
        }
        return result;
    }

    /**
     * 修改订单状态\n" +
     *             "如果使用优惠劵（增加优惠劵）
     * @param serviceOrderId 服务商品订单id
     * @return
     */
    @PutMapping("/updateCancelServiceOrder")
    @ApiOperation("用户取消服务订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceOrderId", value = "服务订单id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateCancelServiceOrder(Integer serviceOrderId) {
        //todo 拿到userId
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        Result result = serviceOrderApi.updateServiceOrderStatus(serviceOrderId, 2);
        Result serviceOrderById = serviceOrderApi.getServiceOrderById(serviceOrderId);
        ServiceOrder serviceOrder = JSONObject.parseObject(JSON.toJSONString(serviceOrderById.getData()), ServiceOrder.class);
        Double serviceOrderPracticalTotal = serviceOrder.getServiceOrderPracticalTotal().doubleValue();
        Double serviceOrderTotal = serviceOrder.getServiceOrderTotal().doubleValue();
        Double price = serviceOrderTotal - serviceOrderPracticalTotal;
        if(price!=0){
            Result couponByPrice = marketingApi.getCouponByPrice(price);
            TCoupon coupon = JSONObject.parseObject(JSON.toJSONString(couponByPrice.getData()), TCoupon.class);
            AddCouponForm addCouponForm = new AddCouponForm();
            addCouponForm.setUserId(userId);
            addCouponForm.setCouponId(coupon.getCouponId());
            addCouponForm.setNumber(1);
            userAPI.insetCouponByUserId(addCouponForm);
        }
        if(serviceOrder.getServiceOrderPayType()==2){
            userAPI.addUserBalanceByUserId(userId,serviceOrderPracticalTotal);
        }
        return Result.success("修改成功",true);
    }

    /**
     * 修改商品库存\n" +
     *             "如果是钱包支付,修改用户钱包余额\n" +
     *             "如果使用优惠劵（增加优惠劵）\n" +
     *             "修改用户积分\n" +
     *             "(如果是钱包支付)增加平台收益，减少店铺收益\n" +
     *             "(如果不是钱包支付)减少店铺收益\n" +
     *             "修改订单状态
     * @param orderId 商品订单id
     * @return
     */
    @PutMapping("/updateUserReturnGoods")
    @ApiOperation("用户退货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "商品订单id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateUserReturnGoods(Integer orderId) {


        return null;
    }


    @PutMapping("/updateUserChangeGoods")
    @ApiOperation("商品换货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "商品订单id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateUserChangeGoods(Integer orderId) {
        return null;
    }

    /**
     * 已经支付未使用  取消服务订单 如果是钱包支付,修改用户钱包余额\n" +
     "如果使用优惠劵（增加优惠劵）\n" +
     "修改用户积分\n" +
     "(如果是钱包支付)增加、减少平台收益，减少店铺收益\n" +
     "(如果不是钱包支付)减少店铺收益，减少平台收益\n" +
     "修改订单状态
     * @param serviceOrderId 服务商品订单id
     * @return
     */
    @PutMapping("/updateUserReturnServiceGoods")
    @ApiOperation("服务商品取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serviceOrderId", value = "服务订单id", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = Boolean.class)})
    @Override
    public Result updateUserReturnServiceGoods(Integer serviceOrderId) {
        Integer userId = JwtUtil.getUserId();
//        Integer userId = 1;
        Result serviceOrderById = serviceOrderApi.getServiceOrderById(serviceOrderId);
        ServiceOrder serviceOrder = JSONObject.parseObject(JSON.toJSONString(serviceOrderById.getData()), ServiceOrder.class);
        Integer goodOrderPayType = serviceOrder.getServiceOrderPayType();
        Double serviceOrderPracticalTotal = serviceOrder.getServiceOrderPracticalTotal().doubleValue();
        Double serviceOrderTotal = serviceOrder.getServiceOrderTotal().doubleValue();
        Double price = serviceOrderTotal - serviceOrderPracticalTotal;

        //加入各种流水

        // 1.店铺流水
        Integer storeId = serviceOrder.getServiceOrderStoreId();
        StoreRevenueInsertForm storeRevenueInsertForm = new StoreRevenueInsertForm();
        storeRevenueInsertForm.setStoreRevenueRetype(2);
        storeRevenueInsertForm.setStoreRevenuePrice(serviceOrderPracticalTotal);
        storeRevenueInsertForm.setStoreRevenueType(3);
        storeRevenueInsertForm.setStoreRevenueServiceOrderId(serviceOrderId);
        storeRevenueInsertForm.setStoreRevenueStoreId(storeId);
        storeRevenueApi.insertStoreRevenue(storeRevenueInsertForm);

        //2.减少平台收益
        PlatformRevenueForm platformRevenueForm = new PlatformRevenueForm();
        platformRevenueForm.setPlatformRevenueRetype("EXPEND");
        platformRevenueForm.setPlatformRevenuePrice(new BigDecimal(serviceOrderPracticalTotal));
        platformRevenueForm.setPlatformRevenueUserId(userId);
        platformRevenueForm.setPlatformRevenueServiceCommissionId(rid);
        platformRevenueForm.setPlatformRevenueType(3);
        platformAccountApi.insertPlatformRevenue(platformRevenueForm);

        if(goodOrderPayType==2){
            //余额支付 增加收益 同时返还余额
            PlatformRevenueForm platformRevenueForm1 = new PlatformRevenueForm();
            platformRevenueForm1.setPlatformRevenueRetype("EARING 收入用户余额");
            platformRevenueForm1.setPlatformRevenuePrice(new BigDecimal(serviceOrderPracticalTotal));
            platformRevenueForm1.setPlatformRevenueUserId(userId);
            platformRevenueForm1.setPlatformRevenueServiceCommissionId(rid);
            platformRevenueForm1.setPlatformRevenueType(3);
            platformAccountApi.insertPlatformRevenue(platformRevenueForm1);

        }


        //返回优惠券
        if(price!=0){
            Result couponByPrice = marketingApi.getCouponByPrice(price);
            TCoupon coupon = JSONObject.parseObject(JSON.toJSONString(couponByPrice.getData()), TCoupon.class);
            AddCouponForm addCouponForm = new AddCouponForm();
            addCouponForm.setUserId(userId);
            addCouponForm.setCouponId(coupon.getCouponId());
            addCouponForm.setNumber(1);
            userAPI.insetCouponByUserId(addCouponForm);
        }

        Result result = serviceOrderApi.updateServiceOrderStatus(serviceOrderId, 2);
        return null;
    }

    @Override
    public Result servicePayBack(HttpServletRequest request) {
        return null;
    }
}
